package com.admin.servlet;

import com.admin.service.IAdminService;
import com.admin.service.impl.AdminServiceImpl;
import com.user.entity.Users;
import com.user.service.IUserService;
import com.user.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ChangeUserInfoServlet", value = "/ChangeUserInfoServlet")
public class ChangeUserInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        int id = Integer.parseInt(request.getParameter("id"));
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String schoolname = request.getParameter("schoolname");

        IAdminService adminService = new AdminServiceImpl();
        IUserService userService = new UserServiceImpl();


        Users users = new Users(id, username, password, schoolname);
        if (!(adminService.IsExistSchoolname(schoolname))) {
            request.setAttribute("msg", "学校名不存在！");

            request.getRequestDispatcher("Admin/adminUpdateUsers.jsp").forward(request, response);
        } else if ((userService.queryUsernameIsExist(new Users(username, "0")))) {
            request.setAttribute("msg", "姓名已存在！");

            request.getRequestDispatcher("Admin/adminUpdateUsers.jsp").forward(request, response);
        } else if (adminService.updateUserInfo(users, id)) {
            request.setAttribute("msg", "修改成功！");

            request.getRequestDispatcher("/UserListServlet").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
